<template>
  <div>
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="45%" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="110px">
        <el-form-item label="仓库编号" prop="code">
          <el-input v-model="formData.code" placeholder="请输入仓库编号"/>
        </el-form-item>
        <el-form-item label="仓库名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入仓库名称"/>
        </el-form-item>
        <el-form-item label="地区" prop="areaId">
          <el-cascader :options="addrOptions"
                       v-model="selectOption"
                       @change="handleChange"
                       clearable
                       placeholder="请选择省/市"></el-cascader>
        </el-form-item>
        <el-form-item label="先进先出" prop="firstInOut">
          <el-radio-group v-model="formData.firstInOut">
            <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.INFRA_BOOLEAN_STRING)"
                      :key="dict.value" :label="dict.value === 'true'">{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="有出库区" prop="haveWaitingArea">
          <el-radio-group v-model="formData.haveWaitingArea">
            <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.INFRA_BOOLEAN_STRING)"
                      :key="dict.value" :label="dict.value === 'true'">{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="分类" prop="warehouseType">
          <el-select v-model="formData.warehouseType" placeholder="请选择分类">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.WAREHOUSE_TYPE)"
                       :key="dict.value" :label="dict.label" :value="dict.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="经纬度" prop="longitudeLatitude">
          <el-input v-model="formData.longitudeLatitude" placeholder="请输入仓库所在经纬度，英文逗号分隔"/>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <treeselect v-model="formData.deptId" :options="deptOptions" :show-count="true" :clearable="false"
                      placeholder="请选择归属部门" :normalizer="normalizer"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import * as WarehouseApi from '@/api/hs/warehouse';
import {getAreaById, getAreaTree} from "@/api/system/area";
import {DICT_TYPE} from "@/utils/dict";
import {listSimpleDepts} from "@/api/system/dept";

export default {
  name: "WarehouseForm",
  computed: {
    DICT_TYPE() {
      return DICT_TYPE
    }
  },
  components: { Treeselect },
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        code: undefined,
        name: undefined,
        areaId: undefined,
        firstInOut: false,
        haveWaitingArea: false,
        warehouseType: undefined,
        longitudeLatitude: undefined,
        deptId: undefined,
      },
      // 表单校验
      formRules: {
        code: [{required: true, message: '仓库编号不能为空', trigger: 'blur'}],
        name: [{required: true, message: '仓库名称不能为空', trigger: 'blur'}],
        areaId: [{required: true, message: '地区编号不能为空', trigger: 'change'}],
        firstInOut: [{required: true, message: '是否需要先进先出不能为空', trigger: 'blur'}],
        haveWaitingArea: [{required: true, message: '是否有出库区不能为空', trigger: 'blur'}],
        warehouseType: [{required: true, message: '分类不能为空', trigger: 'change'}],
        longitudeLatitude: [
            {required: true, message: '仓库所在经纬度不能为空', trigger: 'change'},
            {
                validator: (rule, value, callback) => {
                    if (!value) {
                        callback();
                        return;
                    }
                    // 检查是否包含空格
                    if (/\s/.test(value)) {
                        callback(new Error('经纬度不能包含空格'));
                        return;
                    }
                    // 检查是否包含且仅包含一个英文逗号
                    const commaMatches = value.match(/,/g);
                    if (!commaMatches || commaMatches.length !== 1) {
                        callback(new Error('经纬度必须包含且仅包含一个英文逗号'));
                        return;
                    }
                    // 按逗号分割
                    const parts = value.split(',');
                    if (parts.length !== 2) {
                        callback(new Error('经纬度格式不正确，应为"经度,纬度"格式'));
                        return;
                    }
                    // 检查两部分是否都为数字（包括小数）
                    const [longitudeStr, latitudeStr] = parts;
                    if (longitudeStr === '' || latitudeStr === '') {
                        callback(new Error('经度和纬度不能为空'));
                        return;
                    }
                    const longitude = parseFloat(longitudeStr);
                    const latitude = parseFloat(latitudeStr);

                    if (isNaN(longitude) || isNaN(latitude)) {
                        callback(new Error('经度和纬度必须为数字'));
                        return;
                    }
                    callback();
                },
                trigger: 'blur'
            }
        ]
      },
      addrOptions: [],
      selectOption: [],
      // 部门树选项
      deptOptions: undefined,
    };
  },
  created() {
    this.getTreeselect();
  },
  methods: {
    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      await this.getAreaData();
      this.reset();
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await WarehouseApi.getWarehouse(id);
          this.formData = res.data;
          if (this.formData.areaId) {
            await getAreaById(this.formData.areaId).then(areaRes => {
              this.selectOption = [areaRes.data.parent.id, areaRes.data.id]
            })
          }
          this.dialogTitle = "修改仓库信息";
        } finally {
          this.formLoading = false;
        }
        return
      }
      this.dialogTitle = "新增仓库信息";
    },
    /** 查询省市区 */
    getAreaData() {
      getAreaTree().then(response => {
        this.addrOptions = response.data.map(item => {
          return {
            label: item.name,
            value: item.id,
            children: item.children.map(childrenItem => {
              return {
                label: childrenItem.name,
                value: childrenItem.id,
              }
            })
          }
        })
      })
    },
    handleChange() {
      if (this.selectOption.length > 0) {
        this.formData.areaId = this.selectOption[1];
      } else {
        this.formData.areaId = undefined
      }
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await WarehouseApi.updateWarehouse(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await WarehouseApi.createWarehouse(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.selectOption = []
      this.formData = {
        id: undefined,
        code: undefined,
        name: undefined,
        areaId: undefined,
        firstInOut: false,
        haveWaitingArea: false,
        warehouseType: undefined,
      };
      this.resetForm("formRef");
    },
    /** 查询部门下拉树结构 + 岗位下拉 */
    getTreeselect() {
      listSimpleDepts().then(response => {
        // 处理 deptOptions 参数
        this.deptOptions = [];
        this.deptOptions.push(...this.handleTree(response.data, "id"));
      });
    },
    // 格式化部门的下拉框
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
  }
};
</script>
